﻿using System;
using System.Text;

using LeanEngine.Extensions;
using LeanEngine.Exception;

namespace LeanEngine.Validation
{
    /// <summary>
    /// Attribute to validate if the property has a not null value.
    /// </summary>
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public sealed class IsNotNullAttribute : ValidationAttribute
    {
        #region Constructor Members

        /// <summary>
        /// Initialize a new instance of LeanEngine.Validation.IsNotNullAndHasPrimaryKeysFilledAttribute class with an error message obtained from a resource file.
        /// </summary>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <param name="resourceType">The System.Type of the resource manager that holds the error message.</param>
        /// <param name="errorKey">The key error message contained in the resource.</param>
        public IsNotNullAttribute(Type resourceType, string errorKey)
            : base(resourceType, errorKey) { }

        /// <summary>
        /// Initialize a new instance of LeanEngine.Validation.IsNotNullAndHasPrimaryKeysFilledAttribute class with an specific error message.
        /// </summary>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <param name="errorMessage">The error message displayed for non valid values.</param>
        public IsNotNullAttribute(string errorMessage)
            : base(errorMessage) { }

        #endregion

        #region ValidationAttribute Members

        /// <summary>
        /// Validates the value according to the validation rule and throws an exception in case of validation failure.
        /// </summary>
        /// <exception cref="LeanEngine.Exception.BusinessException"></exception>
        /// <exception cref="System.ArgumentException"></exception>
        /// <param name="value">The value to be validated.</param>
        public override bool Validate(object value)
        {
            if (value.IsNull()) { throw new BusinessException(this.ErrorMessage); }

            return true;
        }

        /// <summary>
        /// Validates the value according to the validation rule to the container and adds exception error in case of validation failure.
        /// </summary>
        /// <exception cref="System.ArgumentException"></exception>
        /// <param name="value">The value to be validated.</param>
        /// <param name="errorMessageContainer">The container for all the error messages.</param>
        public override void Validate(object value, StringBuilder errorMessageContainer)
        {
            if (value.IsNull())
            {
                errorMessageContainer.Append(this.ErrorMessage);
                errorMessageContainer.Append(Environment.NewLine);
            }
        }

        #endregion
    }
}
